package com.wyl.utils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import com.wyl.model.News;
import com.wyl.model.Simple;


public class Utils {




	public static Date parseTime(String time,String format){
		SimpleDateFormat sdf = new SimpleDateFormat(format);  //"MM/dd/yyyy HH:mm:ss"
		Date date=null;  
		try {
			date = sdf.parse(time);
		} catch (ParseException e) {
			System.out.println(time);
		}

		return date;
	}

	public static Map<String, String> getUrlMap(){
		Map<String, String> urlMap = new HashMap<String, String>();
		urlMap.put("http://temp.163.com/special/00804KVA/cm_war.js?callback=data_callback","war");
		urlMap.put( "http://sports.163.com/special/000587PR/newsdata_n_index.js","sport");
		urlMap.put( "http://tech.163.com/special/00097UHL/tech_datalist.js?callback=data_callback","tech");
		urlMap.put( "http://edu.163.com/special/002987KB/newsdata_edu_hot.js?callback=data_callback","edu");
		urlMap.put( "http://ent.163.com/special/000380VU/newsdata_index.js?callback=data_callback","ent");
		urlMap.put( "http://money.163.com/special/002557S5/newsdata_idx_index.js?callback=data_callback","money");
		urlMap.put( "http://money.163.com/special/002557S6/newsdata_gp_index.js?callback=data_callback","gupiao");
		urlMap.put("http://travel.163.com/special/00067VEJ/newsdatas_travel.js?callback=data_callback","travel");
		urlMap.put( "http://lady.163.com/special/00264OOD/data_nd_fashion.js?callback=data_callback","lady");
		return urlMap;
	}

	/**
	 * 将json 数据封装为列表
	 * @param data json数据
	 * @return 封装好的newsList
	 */
	public static List<News> getNewsList(String data){
		ObjectMapper objectMapper = new ObjectMapper();
		News[] newsList=null;
		try {
			newsList = objectMapper.readValue(data, News[].class);

		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		List<News> list = new ArrayList<News>(); 
		for(News n:newsList){
			if(n.getNewstype().equals("article")){
				list.add(n);
			}
		}
		return list;
	}

	/**
	 * 将json映射类News转换为Simple类
	 * @param list newsList
	 * @return simpleList
	 */
	public static List<Simple> transToSimple(List<News> list){
		List<Simple> sl = new ArrayList<Simple>();
		for(News n: list){
			Simple temp = new Simple();
			temp.setTitle(n.getTitle());
			temp.setDocurl(n.getDocurl());
			temp.setChannelname(n.getChannelname());
			temp.setTime(Utils.parseTime(n.getTime(),"MM/dd/yyyy HH:mm:ss"));
			temp.setImgurl(n.getImgurl());
			sl.add(temp);
		}
		return sl;
	}

}
